import Vue from "vue";
import VueRouter from "vue-router";

import SamHome from '@/pages/Home/SamHome'
import SamMember from '@/pages/Member/SamMember'
import ShowGoods from '@/pages/Home/Goods/ShowGoods'
import GoodsDetail from '@/pages/Detail/GoodsDetail'
import SamCart from '@/pages/Cart/SamCart'
import SamLogin from '@/pages/Login/SamLogin'
import SamRegister from '@/pages/Register/SamRegister'
import SamSearch from '@/pages/Search/SamSearch'

Vue.use(VueRouter)

const router = new VueRouter({
  // 切换到详情页，保证滚动条在最顶端
  scrollBehavior (to,from,savedPosition) {
    if(to.name === 'detail' || to.name === 'member'){
      return { x: 0, y: 0 }
    }else if(to.name === 'goods'){
      return savedPosition
    }
    
  },
  routes: [
    {
      path: '/home',
      name:'home',
      component: SamHome,
      children: [
        {
          // 携带params参数的路由组件，多个router-link切换到同一个路由
          name:'goods',
          path: "goods/:id",
          component: ShowGoods
        },
        {
          path: '/home',
          redirect: '/home/goods/001'
        }
      ]
    },
    {
      path: '/member',
      name:'member',
      component: SamMember
    },
    {
      path:'/detail/:id',
      name:'detail',
      component:GoodsDetail,
    },
    {
      path:'/cart',
      name:"cart",
      component:SamCart
    },
    {
      path:'/login',
      name:'login',
      component:SamLogin
    },
    {
      path:'/register',
      name:'register',
      component:SamRegister
    },
    {
      path:'/search',
      component:SamSearch,
    },
    // 重定向
    {
      path: '/',
      redirect: '/home/goods/001'
    },
  ]
})

router.beforeEach((to,from,next)=>{
  let user = localStorage.getItem('status')
  if(user){
    if(to.name === 'regiser' || to.name === 'login'){
      next({name:from.name})
    }else{
      next()
    }
  }else{
    next()
  }
})

export default router

